package com.cszy.yydqbfq.ui.activity

import android.animation.ObjectAnimator
import android.app.ActivityManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.support.v4.media.session.PlaybackStateCompat.REPEAT_MODE_NONE
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.view.animation.LinearInterpolator
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import androidx.viewpager2.widget.ViewPager2
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.hbcysd.qybfq.R
import com.hbcysd.qybfq.databinding.ActivityMainBinding
import com.cszy.yydqbfq.base.BaseEvent

import com.cszy.yydqbfq.base.BaseVMActivity
import com.cszy.yydqbfq.common.AppConstants

import com.cszy.yydqbfq.dialog.BottomPopupWithRecycler
import com.cszy.yydqbfq.ext.clickWithTrigger
import com.cszy.yydqbfq.ext.toast
import com.cszy.yydqbfq.listener.GlobaiPlayListener
import com.cszy.yydqbfq.utils.SpUtils

import com.cszy.yydqbfq.viewmodel.MainViewModel
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.hlyj.http.base.tool.lib_hlyj_base.BaseApplication
import com.hlyj.http.base.tool.lib_hlyj_base.utils.BaseAppConstans
import com.hlyj.http.base.tool.lib_hlyj_base.utils.BaseModuleSpUtils

import com.hnyr.kdcxzs.application.MyApplication
import com.hnyyac.ad.mds.GMAds
import com.hnyyac.ad.mds.IAdType
import com.hnyyac.ad.mds.IAdView
import com.hnyyac.ad.mds.IAdViewListener
import com.hnyyac.ad.mds.utils.BaseAdConstants
import com.hnyyac.ad.mds.views_notload.PangleBannerAdHelper
import com.jw.qiliprj.maintab.adapter.ViewPagerAdapter
import com.lzx.starrysky.OnPlayerEventListener
import com.lzx.starrysky.SongInfo
import com.lzx.starrysky.StarrySky
import com.lzx.starrysky.StarrySky.with
import com.lzx.starrysky.manager.PlaybackStage
import com.lzx.starrysky.service.MusicService
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch


class MainActivity : BaseVMActivity<MainViewModel, ActivityMainBinding>(),
    GlobaiPlayListener, IAdViewListener {
    private var firstClick: Long = 0
    private var tabshowAd: String? = null // 记录当前点击的 Tab 位置
    private var rotateAnimator: ObjectAnimator? = null
    private lateinit var bannerHelper: PangleBannerAdHelper

    private var app_progress : String?  =  null

    override fun initView(savedInstanceState: Bundle?) {
        (application as MyApplication).registerPlaybackListener(this)
        app_progress = SpUtils.getInstance().getString(BaseAppConstans.APP_PROCESS)

        val viewPager = findViewById<ViewPager2>(R.id.viewPager)
        val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottomNavigationView)
        viewPager.isUserInputEnabled = false // 禁用滑动
        // 设置 ViewPager2 的适配器
        viewPager.adapter = ViewPagerAdapter(this,app_progress == "0")
        // 监听底部导航栏的点击事件
        // 监听底部导航栏的点击事件
        bottomNavigationView.setOnNavigationItemSelectedListener { item ->
            when (item.itemId) {
                R.id.navigation_home -> {
                    viewPager.currentItem = 0
                    tabshowAd = "tab1"
                    showADIfNeeded(0)
                }

                R.id.navigation_network -> {
                    viewPager.currentItem = if (isBlack()) 0 else 1
                    tabshowAd = "tab2"
                    showADIfNeeded(1)
                }

                R.id.navigation_wode -> {
                    viewPager.currentItem = if (isBlack()) 1 else 2
                    tabshowAd = "tab4"
                    showADIfNeeded(2)
                }
            }
            true

        }
        // 监听 ViewPager2 的页面切换事件
        viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                bottomNavigationView.menu.getItem(position).isChecked = true
            }
        })


        if (isBlack ()) {
            bottomNavigationView.menu.getItem(0).isVisible = false
            // 添加延时确保UI完全加载后再设置选中状态
            Handler(Looper.getMainLooper()).postDelayed({
                bottomNavigationView.menu.getItem(1).isChecked = true
            }, 100) // 延时100毫秒
        }
        mBinding.bottomNavigationView?.itemIconTintList = null
    }


    fun isBlack(): Boolean {
        return app_progress?.equals("0") ?: false
    }

    override fun initData() {

        // 初始化Banner广告帮助类
        bannerHelper = PangleBannerAdHelper(
            context = this,
            mediaId = BaseAdConstants.BANNER_Id,
            container = mBinding.frameLayoutBanner,
            position = 18
        )
        bannerHelper.loadBannerAd()

        if (app_progress == "0") return
        //BaseApplication.instance.startTimer()
        with().setRepeatMode(REPEAT_MODE_NONE, true)
    }


    override fun initListener() {
        mBinding.rvFlotView.setOnClickListener {
            var listSongs = with().getPlayList()
            val intent = Intent(this, PlayDetailActivity::class.java).apply {
                putParcelableArrayListExtra("MUSIC_LIST", ArrayList(listSongs))
                putExtra("CURRENT_POSITION", with().getNowPlayingIndex())
            }
            startActivity(intent)

        }
        mBinding.ivDetail.setOnClickListener {
            var listSongs = with().getPlayList()

            BottomPopupWithRecycler(this, listSongs!!).show(
                it,
                with().getNowPlayingIndex()
            )
        }

        mBinding.ivNextSong.clickWithTrigger {
            playNextSong()
        }

        mBinding.ivStopPlaySong.clickWithTrigger {
            if (with().isPlaying()) {
                with().pauseMusic()
                mBinding.ivStopPlaySong?.background =
                    ContextCompat.getDrawable(this, R.mipmap.ic_stop_song)
            } else {
                with().restoreMusic()
                mBinding.ivStopPlaySong?.background =
                    ContextCompat.getDrawable(this, R.mipmap.ic_start_song)
            }
        }

    }

    private fun playNextSong() {
        // 1. 获取 PlayerController 和 PlaybackState
        val isSkipToNextEnabled = with().isSkipToNextEnabled()

// 3. 计算下一首的索引 (注意边界检查)
        if (isSkipToNextEnabled) {
            with().skipToNext()
        } else {
            Toast.makeText(this, "没有下一首了", Toast.LENGTH_SHORT).show()
        }
    }

    //    // 新增：检查并显示 Toast（每个 Tab 只弹一次）
    private fun showADIfNeeded(tabPosition: Int) {
        var tab1 = SpUtils.getInstance().getBoolean(BaseAppConstans.IS_show_TAB1, false)
        var tab2 = SpUtils.getInstance().getBoolean(BaseAppConstans.IS_show_TAB2, false)
        var tab3 = SpUtils.getInstance().getBoolean(BaseAppConstans.IS_show_TAB3, false)
        var tab4 = SpUtils.getInstance().getBoolean(BaseAppConstans.IS_show_TAB4, false)
        if (tabPosition == 0 && !tab1) {
            loadAndShowAd(29)
        }
        if (tabPosition == 1 && !tab2) {
            loadAndShowAd(23)
        }
        if (tabPosition == 2 && !tab3) {
            loadAndShowAd(27)
        }

        if (tabPosition == 3 && !tab4) {
            loadAndShowAd(28)
        }
    }

    private fun loadAndShowAd(position: Int) {
        GMAds.loadAd(this, position, IAdType.interstitial).observeForever { ad ->
            if (ad != null) {
                ad.setOnShowingListener(this)
                ad.show(this)
                // loadChapin(contentLayoutIndex, context, listener)
            } else {
                // 广告加载失败，提示用户
                //  currentTabPosition = -1  // 重置位置
                //Toast.makeText(this@IndexMainAcvity, "广告加载失败，请稍后重试", Toast.LENGTH_SHORT).show()

            }
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onAppExit()
            return true
        }
        return false
    }


    override fun handleEvent(event: BaseEvent) {
        when (event.code) {
            AppConstants.PLAY_STAUS_CHANGE -> {
                when (event.data) {
                    PlaybackStage.PAUSE -> {
                        // 暂停状态处理
                        mBinding.ivStopPlaySong?.background =
                            ContextCompat.getDrawable(this@MainActivity, R.mipmap.ic_stop_song)
                    }

                    PlaybackStage.PLAYING -> {
                        mBinding.ivStopPlaySong?.background =
                            ContextCompat.getDrawable(this@MainActivity, R.mipmap.ic_start_song)
                    }
                }
            }
        }
    }

    private fun onAppExit() {
        if (System.currentTimeMillis() - firstClick > 2000L) {
            firstClick = System.currentTimeMillis()
            toast("再按一次退出应用")
            return
        }

        finish()
    }


    private fun startRote() {
        // 顺时针无限旋转 360 度
        rotateAnimator = ObjectAnimator.ofFloat(
            mBinding.ivImgFlot, // 你的 ImageView
            "rotation",         // 动画属性（rotation=绕Z轴旋转）
            0f,                 // 起始角度
            360f                // 结束角度
        ).apply {
            duration = 6000     // 动画时长（毫秒）
            repeatCount = ObjectAnimator.INFINITE  // 无限循环
            interpolator = LinearInterpolator()    // 匀速旋转（避免卡顿）
        }
        rotateAnimator?.start()


    }


    override fun onDestroy() {
        super.onDestroy()
        rotateAnimator?.cancel()
        (application as MyApplication).unregisterPlaybackListener(this)
        bannerHelper.destroy()
    }


    override fun onResume() {
        super.onResume()
        // 绑定服务（复用Application的绑定，无需重新创建）
        bindService(
            Intent(this, MusicService::class.java),
            serviceConnection,
            BIND_AUTO_CREATE
        )

    }


    override fun onPlayback(stage: PlaybackStage) {
        Log.e("qin", "这里就是全局回调")
        val songInfo = stage.songInfo
        mBinding.rvFlotView.visibility = View.VISIBLE
        Glide.with(this)
            .load(songInfo?.coverBitmap)
            .placeholder(R.mipmap.ic_default)
            .error(R.mipmap.ic_default)
            .apply(RequestOptions.circleCropTransform()) // 关键代码：圆形裁剪
            .into(mBinding.ivImgFlot)

        mBinding.tvMusicName.text = songInfo?.songName + "-" + songInfo?.artist
        startRote()
    }

    private val serviceConnection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName?, binder: IBinder?) {
            // 服务已连接，获取服务实例（若需交互）
            Log.d("MusicService", "服务已连接: $name")
            //延迟200ms
            // 使用协程延迟 2 秒
            lifecycleScope.launch {
                delay(200) // 200ms //这里一定要设置延迟 不然不执行
                var songInfo = with().getNowPlayingSongInfo()
                if (songInfo != null) {
                    mBinding.rvFlotView.visibility = View.VISIBLE
                    Glide.with(this@MainActivity)
                        .load(songInfo?.coverBitmap)
                        .placeholder(R.mipmap.ic_default)
                        .error(R.mipmap.ic_default)
                        .apply(RequestOptions.circleCropTransform()) // 关键代码：圆形裁剪
                        .into(mBinding.ivImgFlot)

                    mBinding.tvMusicName.text = songInfo?.songName + "-" + songInfo?.artist
                    startRote()
                }
            }

        }

        override fun onServiceDisconnected(name: ComponentName?) {
            Log.e("MusicService", "服务断开: $name")
        }
    }

    override fun onTrigger(adView: IAdView) {

    }

    override fun onAdShow(adView: IAdView) {

    }

    override fun onAdClick(adView: IAdView) {

    }

    override fun onAdClose(adView: IAdView) {
        when (tabshowAd) {
            "tab1" -> {
                SpUtils.getInstance().putBoolean(BaseAppConstans.IS_show_TAB1, true)
            }

            "tab2" -> {
                SpUtils.getInstance().putBoolean(BaseAppConstans.IS_show_TAB2, true)
            }

            "tab3" -> {
                SpUtils.getInstance().putBoolean(BaseAppConstans.IS_show_TAB3, true)
            }

            "tab4" -> {
                SpUtils.getInstance().putBoolean(BaseAppConstans.IS_show_TAB4, true)
            }

        }
    }

    override fun onError(msg: String) {

    }

    override fun onLoadError(adView: IAdView) {

    }

    override fun onSuccess(adView: IAdView) {

    }

    override fun onLoad(adView: IAdView) {

    }

    override fun onSkipped() {

    }

    override fun onNoAd() {

    }

    override fun onTimeOut() {

    }

    override val isRegisterEvent: Boolean
        get() = true


}


